package com.cy.store.controller;

import com.cy.store.controller.ex.*;
import com.cy.store.pojo.User;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.InsertException;
import com.cy.store.service.ex.UsernameDuplicatedException;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @PROJECT_NAME: store
 * @DESCRIPTION:
 * @USER: 28416
 * @DATE: 2022/11/2 20:18
 */

@RestController
@RequestMapping("users")
public class UserController   extends  BaseController{

    @Autowired
    private IUserService userService;

    /**
     * 原先的代码
     *
     * @RequestMapping("reg")

    public JsonResult<Void> reg(User user){
        //创建结果响应对象
        JsonResult<Void> voidJsonResult = new JsonResult<>();
        try {
            userService.reg(user);
            voidJsonResult.setState(200);
            voidJsonResult.setMessage("用户注册成功");
        } catch (UsernameDuplicatedException e) {
            voidJsonResult.setState(4000);
            voidJsonResult.setMessage("用户名被占用");
        }
        catch (InsertException e) {
            voidJsonResult.setState(5000);
            voidJsonResult.setMessage("注册时发生未知的异常");
        }

        return  voidJsonResult;
    }**/
    /**
     * 优化以后的代码
     * @param user
     * @return
     */
    /**
     * 注册
     * @param user
     * @return
     */
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user) {
        userService.reg(user);

        return new JsonResult<>(OK);
    }

    /**
     * 登录
     * @param username
     * @param password
     * @param session
     * @return
     */
    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session){
        User data = userService.login(username, password);
        //向session对象中完成了绑定(全局的session对象)
        session.setAttribute("username",data.getUsername());
        session.setAttribute("uid",data.getUid());


        //获取session中绑定的数据
        System.out.println(getUidFromSession(session));
        System.out.println(getUsernameFromSession(session));

        return new JsonResult<User>(OK,data);
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @param session
     * @return
     */
    @RequestMapping("change_password")
    public JsonResult<Void> changePassword(String oldPassword,String newPassword,HttpSession session){

        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);

        userService.changePassword(uid,username,oldPassword,newPassword);

        return  new JsonResult<Void>(OK);
    }

    /**
     * 个人资料页面内判断用户数据
     * @param session
     * @return
     */
    @RequestMapping("get_by_uid")
    public JsonResult<User> changeUser(HttpSession session){
        Integer uid = getUidFromSession(session);
        User data = userService.getByUid(uid);
        return  new JsonResult<User>(OK,data);
    }

    /**
     * 修改个人资料
     * @param user
     * @param session
     * @return
     */
    @RequestMapping("change_info")
    public JsonResult<Void> changInfo(User user,
                                      HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);

        userService.changeInfo(uid,username,user);  //user 自动装配  只要属性值和

        return new JsonResult<Void>(OK);
    }

    /**
     * 设置上传文件的最大值
     */
    public static  final  int  AVATAR_MAX_SIZE = 10*1024 *1024;
    /**
     * 限制上传文件的类型
     */
    public static final List<String> AVATAR_TYPE = new ArrayList<>();

    static {

        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }

    /**
     * 上传个人头像
     * @param file
     * @param session
     * @return
     */
    @RequestMapping("update_avatar")
    public JsonResult<String> changeAvatar(@RequestParam("file") MultipartFile file,
                                           HttpSession session) throws FileStateException {
        //处理异常
        if (file.isEmpty()) {
            throw  new FileEmptyException("文件为空");
        }
        if (file.getSize() > AVATAR_MAX_SIZE){
            throw new FileSizeException("文件超出了最大的限制");
        }
        //判断问价类型是否为我们规定的文件类型
        String contentType = file.getContentType();
        boolean contains = AVATAR_TYPE.contains(contentType);
        if (!contains) {
            throw new FileTypeException("文件类型不支持");
        }
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        String upload = session.getServletContext().getRealPath("upload");
        File dir = new File(upload);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //获取到文件的名称  uuid工具类来生成一个新的字符串作为文件名
        //例如：avatar01.png
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        int index = originalFilename.lastIndexOf(".");

        String suffix = originalFilename.substring(index);
        //ADADADAJDAJSDASKLDJALSLDJASDJA.png
        String filename = UUID.randomUUID().toString().toUpperCase() +suffix;

        File  dest = new File(dir,filename);//空文件

        //将file中的数据写入到这个空文件中
        try {
            file.transferTo(dest);  //把数据吸入到了文件中
        } catch (IOException e) {
            throw  new FileUploadIoException("文件写异常");
        }catch (FileStateException e) {
            throw  new FileStateException("文件状态异常");
        }
        String avatar =  "/upload/" +filename;
        userService.changeAvatar(uid,avatar,username);
        //返回头像的路径  用于后面展示使用
        return new JsonResult<String>(OK,avatar);

    }
    @RequestMapping("/activation")
    public JsonResult<Void> activationAccont(String confirmCode) {
       userService.activationAccont(confirmCode);

       return new JsonResult<Void>(OK);


    }

}
